package com.granada.aop.aspect;

import com.alibaba.fastjson.JSON;
import com.granada.aop.annotation.LogAnnotation;
import com.granada.constants.Constant;
import com.granada.entity.SysLog;
import com.granada.utils.IPUtils;
import com.granada.utils.JwtTokenUtil;
import com.granada.utils.HttpContextUtils;
import com.granada.utils.MapperBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by huoth on 2018/5/3.
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {
    /**
     * 此处的切点是注解的方式
     * 只要出现 @LogAnnotation注解都会进入
     */
    @Pointcut("@annotation(com.granada.aop.annotation.LogAnnotation)")
    public void logPointCut(){

    }

    /**
     * 环绕增强,相当于MethodInterceptor
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        try {
            saveSysLog(point, time);
        } catch (Exception e) {
            log.error("e={}",e);
        }

        return result;
    }
    /**
     * 把日志保存
     * @Author:      小霍
     * @CreateDate:  2019/10/7 14:32
     * @UpdateUser:
     * @UpdateDate:  2019/10/7 14:32
     * @Version:     0.0.1
     * @param joinPoint
     * @param time
     * @return       void
     * @throws
     */
    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
         LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        if(logAnnotation != null){
            //注解上的描述
            sysLog.setOperation(logAnnotation.title()+"-"+logAnnotation.action());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        log.info("请求{}.{}耗时{}毫秒",className,methodName,time);
        try {
            //请求的参数
            Object[] args = joinPoint.getArgs();
            String params=null;
            if(args.length!=0){
                List<Object> argsList = Arrays.asList(args);
                // 将 HttpServletResponse 和 HttpServletRequest 参数移除，不然会报异常
                List<Object> collect = argsList.stream().filter(o -> !(o instanceof HttpServletResponse || o instanceof HttpServletRequest)).collect(Collectors.toList());
                Object[] newArgs = new Object[]{collect.size()};
                collect.toArray(newArgs);
                params=JSON.toJSONString(newArgs);
            }

            sysLog.setParams(params);
        } catch (Exception e) {

        }
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        log.info("Ip：{}，接口地址：{}，请求方式：{}，入参：{}",sysLog.getIp(),request.getRequestURL(),request.getMethod(),sysLog.getParams());
        //APP注册和登录接口过滤token验证 add by Wu.H 2021-04-09
        String  requesPath = request.getRequestURI();
        //如果请求为小程序或者APP无token状态请求则不记录日志
        if(!requesPath.equals("/app/login/register") && !requesPath.equals("/app/login/appLogin")
                && !requesPath.equals("/app/login/vaildCode") && !requesPath.equals("/api/login/code")
                && !requesPath.equals("/api/login/register") && !requesPath.equals("/api/login/decrypt")
                && !requesPath.equals("/api/login/phone") && !requesPath.equals("/api/client/uploadAvatr")
                && !requesPath.equals("/app/manufactor/login") && !requesPath.contains("/api/manufacturer")
                && !requesPath.contains("/api/repairs/record/list") && !requesPath.contains("/api/message/revert/list")
                && !requesPath.contains("/api/message/list") && !requesPath.contains("/api/EquipmentAndParts/Mountings")
                && !requesPath.contains("/api/client/binding") && !requesPath.contains("/api/client/one")
                && !requesPath.contains("/api/manufacturer/list") && !requesPath.contains("/api/client/one")
                && !requesPath.contains("/api/clientRepairs/equipment")

        ) {
            //用户名
            String  token = request.getHeader(Constant.ACCESS_TOKEN);
            if(!"".equals(token) && token!=null) {
                JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
                Long userId = JwtTokenUtil.getUserId(token);
                String username =jwtTokenUtil.getUserName(token);
                sysLog.setUsername(username);
                sysLog.setUserId(userId);
                sysLog.setTime((int) time);
                sysLog.setId(null);
                sysLog.setCreateTime(new Date());
                log.info(sysLog.toString());
                MapperBeanUtils.getSysLogMapper().insertSelective(sysLog);
            }

        }

    }
}
